<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑设备' : '添加设备'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="default"
    >
      <el-form-item label="设备名称" prop="name" required>
        <el-input
          v-model="formData.name"
          placeholder="请输入设备名称"
        />
      </el-form-item>

      <el-form-item label="连接类型" prop="type" required>
        <el-radio-group v-model="formData.type" @change="onTypeChange">
          <el-radio value="tcp">TCP连接</el-radio>
          <el-radio value="rtu">RTU(RS485)连接</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- TCP配置 -->
      <template v-if="formData.type === 'tcp'">
        <el-form-item label="IP地址" prop="address" required>
          <el-input
            v-model="formData.address"
            placeholder="192.168.1.100"
          />
        </el-form-item>

        <el-form-item label="端口号" prop="port" required>
          <el-input-number
            v-model="formData.port"
            :min="1"
            :max="65535"
            style="width: 100%"
            placeholder="502"
          />
        </el-form-item>
      </template>

      <!-- RTU配置 -->
      <template v-if="formData.type === 'rtu'">
        <el-form-item label="串口设备" prop="address" required>
          <el-select
            v-model="formData.address"
            filterable
            allow-create
            style="width: 100%"
            placeholder="选择或输入串口设备"
          >
            <el-option label="/dev/ttyUSB0" value="/dev/ttyUSB0" />
            <el-option label="/dev/ttyUSB1" value="/dev/ttyUSB1" />
            <el-option label="/dev/ttyAMA0" value="/dev/ttyAMA0" />
            <el-option label="/dev/ttyS0" value="/dev/ttyS0" />
            <el-option label="/dev/ttyS1" value="/dev/ttyS1" />
            <el-option label="COM1" value="COM1" />
            <el-option label="COM2" value="COM2" />
            <el-option label="COM3" value="COM3" />
          </el-select>
        </el-form-item>

        <el-form-item label="波特率" prop="port" required>
          <el-select v-model="formData.port" style="width: 100%">
            <el-option label="1200" :value="1200" />
            <el-option label="2400" :value="2400" />
            <el-option label="4800" :value="4800" />
            <el-option label="9600" :value="9600" />
            <el-option label="19200" :value="19200" />
            <el-option label="38400" :value="38400" />
            <el-option label="57600" :value="57600" />
            <el-option label="115200" :value="115200" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="校验位" prop="parity">
              <el-select v-model="formData.parity" style="width: 100%">
                <el-option label="无校验(N)" value="N" />
                <el-option label="奇校验(O)" value="O" />
                <el-option label="偶校验(E)" value="E" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据位" prop="data_bits">
              <el-select v-model="formData.data_bits" style="width: 100%">
                <el-option label="7位" :value="7" />
                <el-option label="8位" :value="8" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="停止位" prop="stop_bits">
          <el-select v-model="formData.stop_bits" style="width: 200px">
            <el-option label="1位" :value="1" />
            <el-option label="2位" :value="2" />
          </el-select>
        </el-form-item>
      </template>

      <el-form-item label="从站地址" prop="slave_id" required>
        <el-input-number
          v-model="formData.slave_id"
          :min="1"
          :max="247"
          style="width: 200px"
          placeholder="1"
        />
        <span class="form-tip">Modbus从站ID，范围1-247</span>
      </el-form-item>

      <el-form-item label="协议模板" prop="protocol">
        <el-select v-model="formData.protocol" style="width: 100%">
          <el-option label="标准Modbus" value="standard" />
          <el-option label="Monet协议" value="monet" />
          <el-option label="华为协议" value="huawei" />
          <el-option label="中科智赋协议" value="zkzf" />
          <el-option label="自定义协议" value="custom" />
        </el-select>
      </el-form-item>

      <el-form-item label="超时时间(ms)" prop="timeout">
        <el-input-number
          v-model="formData.timeout"
          :min="100"
          :max="10000"
          style="width: 200px"
          placeholder="3000"
        />
      </el-form-item>

      <el-form-item label="启用状态" prop="enabled">
        <el-switch
          v-model="formData.enabled"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <el-form-item label="设备描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="设备描述信息（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ isEdit ? '更新' : '添加' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  device: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'save'])

// Refs
const formRef = ref()
const saving = ref(false)

// Computed
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单数据
const formData = reactive({
  name: '',
  type: 'tcp',
  address: '',
  port: 502,
  slave_id: 1,
  protocol: 'standard',
  timeout: 3000,
  enabled: true,
  description: '',
  // RTU特有字段
  parity: 'N',
  data_bits: 8,
  stop_bits: 1
})

// 表单验证规则
const formRules = computed(() => {
  const baseRules = {
    name: [
      { required: true, message: '请输入设备名称', trigger: 'blur' },
      { min: 2, max: 50, message: '设备名称长度在2-50个字符', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择连接类型', trigger: 'change' }
    ],
    address: [
      { required: true, message: '请输入地址信息', trigger: 'blur' }
    ],
    port: [
      { required: true, message: '请输入端口或波特率', trigger: 'blur' }
    ],
    slave_id: [
      { required: true, message: '请输入从站地址', trigger: 'blur' },
      { type: 'number', min: 1, max: 247, message: '从站地址范围1-247', trigger: 'blur' }
    ]
  }

  // TCP特有验证
  if (formData.type === 'tcp') {
    baseRules.address.push({
      pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: '请输入有效的IP地址',
      trigger: 'blur'
    })
    baseRules.port.push({
      type: 'number',
      min: 1,
      max: 65535,
      message: '端口范围1-65535',
      trigger: 'blur'
    })
  }

  // RTU特有验证
  if (formData.type === 'rtu') {
    baseRules.address.push({
      pattern: /^(\/dev\/tty[A-Z0-9]+|COM[0-9]+)$/i,
      message: '请输入有效的串口设备名',
      trigger: 'blur'
    })
    baseRules.port.push({
      type: 'number',
      min: 1200,
      max: 115200,
      message: '波特率范围1200-115200',
      trigger: 'blur'
    })
  }

  return baseRules
})

// 方法
const onTypeChange = (type) => {
  // 切换连接类型时重置相关字段
  if (type === 'tcp') {
    formData.address = ''
    formData.port = 502
  } else {
    formData.address = '/dev/ttyUSB0'
    formData.port = 9600
    formData.parity = 'N'
    formData.data_bits = 8
    formData.stop_bits = 1
  }
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    saving.value = true

    // 构建保存数据
    const saveData = { ...formData }
    
    // 如果是TCP连接，移除RTU特有字段
    if (saveData.type === 'tcp') {
      delete saveData.parity
      delete saveData.data_bits
      delete saveData.stop_bits
    }

    emit('save', saveData)
    
    ElMessage.success(props.isEdit ? '设备更新成功' : '设备添加成功')
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  visible.value = false
  formRef.value?.clearValidate()
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    type: 'tcp',
    address: '',
    port: 502,
    slave_id: 1,
    protocol: 'standard',
    timeout: 3000,
    enabled: true,
    description: '',
    parity: 'N',
    data_bits: 8,
    stop_bits: 1
  })
}

// 监听设备数据变化
watch(() => props.device, (newDevice) => {
  if (newDevice && Object.keys(newDevice).length > 0) {
    Object.assign(formData, {
      name: newDevice.name || '',
      type: newDevice.type || 'tcp',
      address: newDevice.address || '',
      port: newDevice.port || (newDevice.type === 'tcp' ? 502 : 9600),
      slave_id: newDevice.slave_id || 1,
      protocol: newDevice.protocol || 'standard',
      timeout: newDevice.timeout || 3000,
      enabled: newDevice.enabled !== undefined ? newDevice.enabled : true,
      description: newDevice.description || '',
      // RTU特有字段
      parity: newDevice.parity || 'N',
      data_bits: newDevice.data_bits || 8,
      stop_bits: newDevice.stop_bits || 1
    })
  } else {
    resetForm()
  }
}, { deep: true, immediate: true })
</script>

<style scoped>
.form-tip {
  color: #8c8c8c;
  font-size: 12px;
  margin-left: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>